package com.guet.file.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.guet.common.entity.MyAppConfig;
import com.guet.common.exception.ApiException;
import com.guet.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dragon
 */
@Service
public class FileServiceImpl implements IFileService {

    @Autowired
    MyAppConfig appConfig;

    @Override
    public String saveFile(MultipartFile file) {
        // 获取文件的名称
        String filename = file.getOriginalFilename();
        // 获取文件类型后缀
        String[] split = filename.split("\\.");
        String type = split[split.length - 1];
        // 获取文件大小，字节大小，1k=1024字节
        long fileSize = file.getSize();

        // 判断文件类型是否满足条件
        if (!appConfig.getUploadFileTypes().contains(type.toLowerCase())) {
            throw new ApiException("文件类型不合法");
        }
        // 判断文件大小是否满足条件
        if (appConfig.getUploadFileSize() < fileSize) {
            throw new ApiException("文件超出容量限制");
        }

        // 使用 IO 把文件保存到本地
        // 1、生成一个唯一文件名 b17f24ff026d40949c85a24f4f375d42.png
        String newFileName = IdUtil.simpleUUID() + "." + type;
        // 2、创建文件  D:/images/b17f24ff026d40949c85a24f4f375d42.png
        String ip = null;
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            ip = inetAddress.getHostAddress();

        } catch (IOException io) {
            throw new ApiException("获取IP 出错");
        }


        String path = appConfig.getSaveFilePath() + newFileName;
        File newFile = FileUtil.touch(path);
        // 3、把上传文件的二进制内容写入到当前的空文件中
        try {
            FileUtil.writeBytes(file.getBytes(), newFile);
            // 保存成功，返回文件的HTTP访问地址
            return appConfig.getHttpFilePath() + ip + ":8080/" + newFileName;
        } catch (IOException e) {
            throw new ApiException("写文件出错");
        }
    }

    @Override
    public List<String> saveFiles(MultipartFile[] files) {
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            String url = this.saveFile(file);
            urls.add(url);
        }
        return urls;
    }
}
